import urllib2
import datetime
from sgmllib import SGMLParser

GAME = {'lotto'  : 1,
        'mini'   : 3,
        'multi'  : 2,
        'joker'  : 7,
        'kaskada': 8 };

SIZE = {'lotto'  : 6,
        'mini'   : 5,
        'multi'  : 20,
        'joker'  : 5,
        'kaskada': 12 };

LINK = 'http://serwis.lotto.pl/183-41fa1fbe222f2.htm?id_gra=%i&sortuj=off&numer=%i&data=%s';


class URLLister (SGMLParser):
    def reset (self):
        SGMLParser.reset (self);
        self.use = False;
        self.data = [];
    
    def start_td (self, attrs):
        self.use = True;
    
    def handle_data (self, data):
        if self.use and data != ', ' and data != 'Plus ':
            self.data.append (data);
    
    def end_td (self):
        self.use = False;


class ParseLotto ():
    def __init__ (self):
        self.parser = URLLister ();
        self.link = '';
    
    def _download (self):
        sock = urllib2.urlopen (self.link);
        page = sock.read ();
        sock.close ();
        return page;
    
    def clear (self):
        return self.parser.reset ();

    def parse (self, mode, num):
        d = datetime.date.today ();
        self.link = LINK % (GAME[mode], num, d.strftime ('%d-%m-%Y'));
        html = self._download ();
        self.parser.feed (html);
        self.parser.close ();
        lotto = [];
        i = 0;
        while i < len(self.parser.data):
            lotto.append ((self.parser.data[i],
                           datetime.datetime.strptime (self.parser.data[i+1], '%d-%m-%Y %H:%M').date (),
                           [int(self.parser.data[j]) for j in xrange(i+2, i+SIZE[mode]+2)]));
            i += SIZE[mode] + 3;
        return lotto;
